package org.uim.cricket.updater;

import java.util.Calendar;

import org.uim.cricket.updater.gui.frmUpdator;

public class Updater {

	public static final String UPDATER_BEANS_CONFIG_FILE = "../config/updater-beans.xml";
	
	static {
		System.setProperty("org.apache.commons.logging.Log",
        "org.apache.commons.logging.impl.NoOpLog");
	}
	
	public static void main(String[] args) throws Exception {
		if (args == null || args.length == 0) {
			throw new Exception("Arguments can't be empty for updater!");
		}
		
		Ulogger.printHeader(" Initializing updater... ");
		
		Ulogger.debug(" Loading beans... ");
		UpdateFetchBeans ubeans = new UpdateFetchBeans(UPDATER_BEANS_CONFIG_FILE);
		ubeans.loadBeans();
		Ulogger.debug("   - ok.");
		
		Ulogger.debug(" Loading properties... [" + UpdaterProperties.UPDATER_CONFIG_FILE + "]");
		UpdaterProperties uprop = new UpdaterProperties();
		uprop.load();
		Ulogger.debug("  - ok.");
		
		String repoDir = uprop.getProperty("match.repository.dir");
		String d = uprop.getProperty("last.updated.date");
		
		frmUpdator gui = new frmUpdator(null, true, d, repoDir);
		gui.setVisible(true);
		if (!gui.isDoContinue()) {
			Ulogger.debug(" User cancelled the updating process.");
			Ulogger.debug(" Application quitting.");
			return;
		}
		uprop.setProperty("last.updated.date", gui.getLastUpdatedDate());
		uprop.setProperty("match.repository.dir", gui.getRepositoryDir());
		gui.dispose();
		
		d = uprop.getProperty("last.updated.date");
		String[] parts = d.split("/");
		Calendar c = getLastUpdatedDate();
		if (parts.length == 3) {
			c.set(Calendar.YEAR, Integer.parseInt(parts[0]));
			c.set(Calendar.MONTH, Integer.parseInt(parts[1]) - 1);
			c.set(Calendar.DATE, Integer.parseInt(parts[2]));
			Ulogger.debug(" found update since: " + c.get(Calendar.YEAR) + "/" + (c.get(Calendar.MONTH)+1) + "/" + c.get(Calendar.DATE));
		}
		
		Ulogger.debug(" Updating started with bean [" + args[0] + "]... ");
		Updatable update = ubeans.getUpdateBean(args[0]);
		if (update == null) {
			Ulogger.warn("  Updater can't be empty!");
		}
		boolean success = update.update(c, uprop);
		
		if (success) {
			Ulogger.debug(" Successfully Completed updator!");
		} else {
			Ulogger.error(" FAILED updating. Check for logs.");
		}
		Ulogger.debug(" Application quiting.");
		return;
	}

	private static Calendar getLastUpdatedDate() {
		Calendar cal = Calendar.getInstance();
		
		return cal;
	}
	
}
